
import M from './model.js'
import {calQuadrant,clearCanvas} from './utils.js'

function view (){
    function calImg(index){
        var picArr = M.getPicArr()
        var img = picArr[index]
        return img
    }
    function calPicParam(img){
        var {scaleFactor,initRectangle,mouseEndPosition,k0,currentRectangle,moveVector} = M.getStateData()

        var picLeft,picTop,picWidth,picHeight

        picWidth = initRectangle.width * scaleFactor
        picHeight = initRectangle.height * scaleFactor
        
        var initLeft = (img.width-initRectangle.width)/2
        var initTop = (img.height-initRectangle.height)/2
        
        var screenX = mouseEndPosition.x
        var screenY = mouseEndPosition.y
        var k = currentRectangle ? currentRectangle.width/window.canvasNode.width : k0
        var currentLeft = currentRectangle ?currentRectangle.x : initLeft
        var currentTop = currentRectangle ?currentRectangle.y : initTop

        // 缩放前该点在取图方框里的坐标
        var x1 = screenX * k
        var y1 = screenY * k
        // 缩放后该点在取图方框里的坐标
        var newScale = scaleFactor*(currentRectangle?initRectangle.width/currentRectangle.width:1)
        var x2 = x1*newScale
        var y2 = y1*newScale
        // 根据屏幕坐标求该点在图片上的坐标
        var imgX = x1 + currentLeft
        var imgY = y1 + currentTop
        // 缩放后该点在图片的坐标
        var imgX2 = x2 + currentLeft
        var imgY2 = y2 + currentTop
        // 计算平移量
        var deltax =  imgX - imgX2
        var deltay = imgY - imgY2

        // 计算平移量的最大值和最小值
        var topMax = img.height - initTop - picHeight
        var leftMax = img.width - initLeft - picWidth
        var topMin = initTop
        var leftMin = initLeft

        // 计算因拖动导致的平移量（屏幕坐标）
        var moveVectorX = moveVector.x
        var moveVectorY = moveVector.y
        // 平移向量坐标变换到图片的坐标
        var VectorX = moveVectorX*k
        var VectorY = moveVectorY*k

        var leftResult = currentLeft + deltax - VectorX
        var topResult = currentTop + deltay -  VectorY

        picLeft = Math.min(leftMax,Math.max(leftResult,leftMin)) 
        picTop = Math.min(topMax,Math.max(topResult,topMin)) 
        
        M.setCurrentRectangle(picLeft,picTop,picWidth,picHeight,scaleFactor)
        return {
            picLeft,picTop,picWidth,picHeight
        }
    }
    return {
        drawImage(){
            var picIndex = M.getStateData().picIndex
            var img = calImg(picIndex)
            var {picLeft,picTop,picWidth,picHeight} = calPicParam(img)
            clearCanvas()
            window.canvas2Dctx.drawImage(img,
                picLeft,
                picTop,
                picWidth,
                picHeight,
                0,0,
                window.canvasNode.width,
                window.canvasNode.height,
            )
        },
        drawCanvas(){

        }
    }
}

var V = view()

export default V